<template>
    <div>
      <div class="search-container">
        <el-col :lg="7" :md="8" :sm="12" :xs="24">
          <el-input
            clearable
            v-model="filters.name"
            :placeholder="$t('common.pleaseEnter') + ' ' + $t('permission.name')"
            style="width: 100%;margin-bottom:20px;"
            prefix-icon="el-icon-search"
          >
            <template slot="append">
              <el-button @click="getList">{{ $t('common.search') }}</el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :lg="17" :md="16" :sm="12" :xs="24" style="text-align:right;margin-bottom:20px;">
          <el-button type="primary" @click="resetForm('rightForm');isEdit=false;handleAdd()">{{ $t('permission.add') }}</el-button>
          <el-button type="danger" @click="handleBatchDelete">{{ $t('common.delete') }}</el-button>
        </el-col>
      </div>
      <div class="table-container">
        <el-table :data="tableData" border stripe :header-cell-style="headClass"
                  :cell-style="cellClass" :max-height="tableHeight"
                  @selection-change="handleSelectionChange"
                  v-loading="loading"
                  row-key="id">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID" min-width="80"></el-table-column>
          <el-table-column prop="name" :label="$t('permission.name')" min-width="120"></el-table-column>
          <el-table-column prop="url" :label="$t('permission.url')" min-width="150"></el-table-column>
          <el-table-column prop="type" :label="$t('permission.type')" min-width="120">
            <template slot-scope="scope">
              <el-tag :type="getTypeTagType(scope.row.type)">{{ getTypeLabel(scope.row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" :label="$t('common.status')" min-width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? $t('common.enabled') : $t('common.disabled') }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- PC端操作列 -->
          <el-table-column :label="$t('common.operation')" min-width="180" fixed="right" v-if="!isMobile">
            <template slot-scope="scope">
              <div class="operation-buttons">
                <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)">
                  <i class="el-icon-edit"></i> {{ $t('common.edit') }}
                </el-button>
                <el-popconfirm :title="$t('common.deleteConfirm')" @confirm="handleDelete(scope.$index, scope.row)">
                  <el-button type="danger" size="mini" slot="reference">
                    <i class="el-icon-delete"></i> {{ $t('common.delete') }}
                  </el-button>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
          
          <!-- 移动端操作列 -->
          <el-table-column :label="$t('common.operation')" width="100" fixed="right" v-if="isMobile">
            <template slot-scope="scope">
              <el-popover
                placement="left"
                width="160"
                trigger="click">
                <div class="mobile-operation-buttons">
                  <el-button 
                    type="text" 
                    size="mini" 
                    @click="handleEdit(scope.$index, scope.row)">
                    <i class="el-icon-edit"></i> {{ $t('common.edit') }}
                  </el-button>
                  <el-popconfirm :title="$t('common.deleteConfirm')" @confirm="handleDelete(scope.$index, scope.row)">
                    <el-button 
                      type="text" 
                      size="mini" 
                      slot="reference"
                      class="delete-button">
                      <i class="el-icon-delete"></i> {{ $t('common.delete') }}
                    </el-button>
                  </el-popconfirm>
                </div>
                <el-button slot="reference" type="primary" size="mini">
                  {{ $t('common.operation') }} <i class="el-icon-arrow-down"></i>
                </el-button>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            :layout="paginationLayout"
            :total="total">
        </el-pagination>
      </div>
      <el-dialog :title="$t('permission.info')" :visible.sync="dialogFormVisible" width="90%" :fullscreen="isMobile">
        <el-form :model="form" :rules="rules" ref="rightForm" label-width="100px" :inline="!isMobile" label-position="left">
          <el-form-item :label="$t('permission.name')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('common.pleaseEnter') + ' ' + $t('permission.name')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('permission.url')" prop="url">
            <el-input v-model="form.url" :placeholder="$t('common.pleaseEnter') + ' ' + $t('permission.url')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('permission.type')" prop="type">
            <el-select v-model="form.type" :placeholder="$t('common.pleaseSelect') + ' ' + $t('permission.type')">
              <el-option :label="$t('permission.menu')" :value="1"></el-option>
              <el-option :label="$t('permission.button')" :value="2"></el-option>
              <el-option :label="$t('permission.api')" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('common.status')" prop="status">
            <el-select v-model="form.status" :placeholder="$t('common.pleaseSelect') + ' ' + $t('common.status')">
              <el-option :label="$t('common.enabled')" :value="1"></el-option>
              <el-option :label="$t('common.disabled')" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('common.description')" prop="description" :span="24">
            <el-input type="textarea" v-model="form.description" :placeholder="$t('common.pleaseEnter') + ' ' + $t('common.description')" :rows="3"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">{{ $t('common.cancel') }}</el-button>
          <el-button type="primary" @click="save()" :loading="saveLoading">{{ $t('common.confirm') }}</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import ElementUI from "element-ui";
  
  export default {
    name: "RightManage",
    data() {
      return {
        tableData: [],
        total: 0,
        currentPage: 1,
        pageSize: 10,
        rightName: "",
        filters: {
          name: ""
        },
        form: {
          name: '',
          url: '',
          type: 1,
          status: 1,
          description: ''
        },
        isEdit: false,
        rules: {
          name: [
            { required: true, message: this.$t('common.pleaseEnter') + ' ' + this.$t('permission.name'), trigger: 'blur' },
            { min: 2, max: 50, message: this.$t('common.lengthLimit', { min: 2, max: 50 }), trigger: 'blur' }
          ],
          url: [
            { required: true, message: this.$t('common.pleaseEnter') + ' ' + this.$t('permission.url'), trigger: 'blur' }
          ],
          type: [
            { required: true, message: this.$t('common.pleaseSelect') + ' ' + this.$t('permission.type'), trigger: 'change' }
          ],
          status: [
            { required: true, message: this.$t('common.pleaseSelect') + ' ' + this.$t('common.status'), trigger: 'change' }
          ]
        },
        dialogFormVisible: false,
        rawId: [],
        loading: false,
        saveLoading: false,
        // 响应式设计相关
        isMobile: false,
        tableHeight: 650,
        paginationLayout: "total, sizes, prev, pager, next, jumper",
        screenWidth: document.body.clientWidth
      }
    },
    created() {
      this.loadData()
      this.checkScreenSize()
    },
    mounted() {
      window.addEventListener('resize', this.checkScreenSize)
      this.checkScreenSize()
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.checkScreenSize)
    },
    methods: {
      // 检查屏幕尺寸并设置相应的布局
      checkScreenSize() {
        this.screenWidth = document.body.clientWidth
        this.isMobile = this.screenWidth < 768
        
        // 根据屏幕尺寸调整分页控件布局
        if (this.isMobile) {
          this.paginationLayout = "prev, pager, next"
          this.tableHeight = 450
        } else {
          this.paginationLayout = "total, sizes, prev, pager, next, jumper"
          this.tableHeight = 650
        }
      },
      //设置表头
      headClass() {
        return 'background:#E6F1FF;color:#368CFF;font-size:13px;text-align: center;'
      },
      //设置表样式
      cellClass() {
        return 'text-align: center;'
      },
      //改变显示条数时调用
      handleSizeChange(pageSize) {
        this.pageSize = pageSize
        this.loadData()
      },
      // 改变页码时调用
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage
        this.loadData()
      },
      // 重置搜索条件
      resetSearch() {
        this.rightName = ""
        this.loadData()
      },
      // 获取权限类型标签样式
      getTypeTagType(type) {
        const typeMap = {
          1: 'primary',
          2: 'success',
          3: 'warning'
        }
        return typeMap[type] || 'info'
      },
      // 获取权限类型显示文本
      getTypeLabel(type) {
        const typeMap = {
          1: this.$t('permission.menu'),
          2: this.$t('permission.button'),
          3: this.$t('permission.api')
        }
        return typeMap[type] || type
      },
      //添加/编辑权限
      save() {
        this.$refs.rightForm.validate((valid) => {
          if (valid) {
            this.saveLoading = true
            this.$axios.post("/right/add", this.form).then(res => {
              let data = res;
              if (data.code === 200) {
                ElementUI.Message.success(this.$t('common.operationSuccess'))
                this.dialogFormVisible = false;
                this.loadData()
              } else {
                ElementUI.Message.error(data.msg || this.$t('common.operationFailed'))
              }
            }).catch(err => {
              console.error("保存权限失败", err)
              ElementUI.Message.error(this.$t('common.operationFailedRetry'))
            }).finally(() => {
              this.saveLoading = false
            })
          } else {
            return false;
          }
        });
      },
      // 添加权限
      handleAdd() {
        this.dialogFormVisible = true
        this.form = {
          name: '',
          url: '',
          type: 1,
          status: 1,
          description: ''
        }
        // 重置表单验证
        if (this.$refs.rightForm) {
          this.$refs.rightForm.resetFields()
        }
      },
      // 删除权限
      handleDelete(index, row) {
        this.loading = true
        this.$axios.delete("/right/delete/" + row.id).then(res => {
          let data = res;
          if (data.code === 200) {
            ElementUI.Message.success(this.$t('common.deleteSuccess'))
            this.loadData()
          } else {
            ElementUI.Message.error(data.msg || this.$t('common.deleteFailed'))
          }
        }).catch(err => {
          console.error("删除权限失败", err)
          ElementUI.Message.error(this.$t('common.deleteFailedRetry'))
        }).finally(() => {
          this.loading = false
        })
      },
      // 批量删除权限
      handleBatchDelete() {
        if (this.rawId.length === 0) {
          ElementUI.Message.warning(this.$t('permission.selectFirst'))
          return
        }
        
        this.loading = true
        this.$axios.post("/right/delete/batch/", this.rawId).then(res => {
          let data = res;
          if (data.code === 200) {
            ElementUI.Message.success(this.$t('common.batchDeleteSuccess'))
            this.loadData()
          } else {
            ElementUI.Message.error(data.msg || this.$t('common.batchDeleteFailed'))
          }
        }).catch(err => {
          console.error("批量删除权限失败", err)
          ElementUI.Message.error(this.$t('common.batchDeleteFailedRetry'))
        }).finally(() => {
          this.loading = false
        })
      },
      // 编辑权限
      handleEdit(index, row) {
        this.dialogFormVisible = true
        this.isEdit = true
        this.form = JSON.parse(JSON.stringify(row))
        // 重置表单验证
        this.$nextTick(() => {
          if (this.$refs.rightForm) {
            this.$refs.rightForm.resetFields()
          }
        })
      },
      //多选框事件
      handleSelectionChange(raw) {
        this.rawId = []
        for (let i = 0; i < raw.length; i++) {
          this.rawId.push(raw[i].id);
        }
      },
  
      //加载数据
      loadData() {
        this.loading = true
        this.$axios.get("/right/list", {
          params: {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            rightName: this.rightName,
          }
        }).then(res => {
          let data = res.data;
          this.tableData = data.records;
          this.total = data.total;
        }).catch(err => {
          console.error("加载权限列表失败", err)
          ElementUI.Message.error(this.$t('common.loadFailedRetry'))
        }).finally(() => {
          this.loading = false
        })
      },
      // 搜索
      getList() {
        this.rightName = this.filters.name
        this.loadData()
      },
      // 重置表单
      resetForm(formName) {
        if (this.$refs[formName]) {
          this.$refs[formName].resetFields()
        }
      },
    }
  };
  </script>
  
  <style scoped>
  .search-container {
    margin: 10px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }
  
  .operation-container {
    margin: 10px;
    text-align: left;
  }
  
  .table-container {
    width: 100%;
    overflow-x: auto;
  }
  
  .pagination-container {
    padding: 15px 0;
    display: flex;
    justify-content: center;
  }
  
  .operation-buttons {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 5px;
  }
  
  .operation-button {
    margin-bottom: 5px;
    margin-right: 5px;
  }
  
  .mobile-operation-buttons {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }
  
  .mobile-operation-buttons .el-button {
    margin-left: 0;
    margin-bottom: 8px;
    width: 100%;
    text-align: left;
  }
  
  .mobile-operation-buttons .el-button:last-child {
    margin-bottom: 0;
  }
  
  .mobile-operation-buttons .delete-button {
    color: #F56C6C;
  }
  
  @media screen and (max-width: 768px) {
    .search-container {
      flex-direction: column;
      align-items: flex-start;
    }
    
    .search-container .el-input {
      width: 100%;
      margin-bottom: 10px;
      margin-right: 0;
    }
    
    .search-container .el-button {
      margin-bottom: 5px;
    }
    
    .el-table {
      width: 100%;
      font-size: 12px;
    }
    
    .el-button {
      padding: 7px 10px;
      font-size: 12px;
    }
    
    .el-form-item {
      width: 100%;
    }
    
    .el-select {
      width: 100%;
    }
  }
  </style>